package com.hatricks.is.controller.uploadandconfig;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.system.SystemUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/file")
public class FileUploadController {

    /**
     * <!-- Hutool工具包 -->
     * <dependency>
     * <groupId>cn.hutool</groupId>
     * <artifactId>hutool-all</artifactId>
     * <version>5.8.15</version>
     * </dependency>
     * spring:
     * servlet:
     * multipart:
     * max-file-size: 50MB    # 单个文件最大尺寸
     * max-request-size: 100MB # 总请求最大尺寸
     */
    private static final String BASE_FILE_PATH = "files";
    private static final String BASE_PATH = SystemUtil.getUserInfo().getCurrentDir() + BASE_FILE_PATH + File.separator;

    static {
        //RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths("/api/file/batchupload").methods(RequestMethod.POST).build();
        //Method method = ReflectUtil.getMethod(FileUploadController.class, "batchUpload", MultipartFile[].class);
        //
        //RequestMappingHandlerMapping mapping = SpringUtil.getBean("requestMappingHandlerMapping");
        //FileUploadController controller = new FileUploadController();
        //mapping.registerMapping(requestMappingInfo, controller, method);
    }

    /**
     * 批量上传接口
     *
     * @param files 前端传递的文件数组
     * @return 上传结果
     */
    @PostMapping("/batchupload")
    public void batchUpload(@RequestParam("files") MultipartFile[] files) {
        List<FileInfo> resultList = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    // 生成日期目录结构
                    String datePath = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_PATTERN);
                    String fullPath = BASE_PATH + datePath;
                    // 创建目录（Hutool实现目录递归创建）
                    FileUtil.mkdir(fullPath);
                    // 生成唯一文件名（Hutool UUID+原始文件名）
                    String fileName = IdUtil.fastSimpleUUID() + "_" + file.getOriginalFilename();
                    // 保存文件（Hutool文件操作）
                    File destFile = FileUtil.file(fullPath, fileName);
                    file.transferTo(destFile);
                    // 记录文件信息
                    resultList.add(new FileInfo(fileName, file.getSize(), BASE_FILE_PATH + "/" + datePath + "/" + fileName));
                }
            }
            System.out.println(StrUtil.format("当前存储的文件信息为:[{}]", JSONUtil.toJsonStr(resultList)));
        } catch (IOException e) {
            System.out.println(StrUtil.format("当前文件保存异常,异常信息为:[{}]", e.getMessage()));
        }
    }

    /**
     * 文件信息DTO
     */
    @Data
    @AllArgsConstructor
    public static class FileInfo {
        private String fileName;
        private Long fileSize;
        private String filePath;
    }


    /**
     * 添加当前上传目录为访问的静态目录直接进行静态文件上传下载
     */
    @Configuration
    public static class WebConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler(BASE_FILE_PATH + "/" + "**").addResourceLocations("file:" + SystemUtil.getUserInfo().getCurrentDir() + BASE_FILE_PATH + File.separator);  // 本地磁盘路径
        }
    }

}

